'''
water
2017-08-25
'''

import requests

if __name__ == "__main__":
    url = "https://www.tiobe.com/tiobe-index//"
    s = requests.get(url).text
    s = s.replace("</tr>", "</tr>\n")
    ls = s.split("\n")
    ss = ""
    for l in ls:
        if "<h2>" in l:
            h2 = l
            h2 = h2.replace("<h2>", "")
            h2 = h2.replace("</h2>", "")
            h2 = h2.replace("<b>", "")
            h2 = h2.replace("</b>", "")
            h2 = h2.replace("</p>", "")
            #print(h2)
            if "<b>" in l:
                tit = h2
        elif "<tr" in l:
            if h2 != "":
                ss += h2 + "\n"
                print(h2)
                h2 = ""
            l = l.replace("</td>", "")
            l = l.replace("</tr>", "")
            l = l.replace("<tr>", "")
            r = l.split("<td>")
            if len(r) == 7:
                s1 = "\t%5s %5s %25s %10s %10s" % (r[1], r[2], r[4], r[5], r[6])
                ss += s1 + "\n"
                print(s1)
            elif len(r) == 4:
                s1 = "\t%5s       %25s %10s" % (r[1], r[2], r[3])
                ss += s1 + "\n"
                print(s1)
            elif len(r) == 9:
                s1 = "%25s " % r[1]
                for i in range(2, 9):
                    s1 += "%4s " % r[i]
                ss += s1 + "\n"
                print(s1)
            elif len(r) == 3:
                s2 = r[2].replace('<img src="/images/medal.png" alt="medal"> ', '')
                s1 = "%4s %15s" % (r[1], s2)
                ss += s1 + "\n"
                print(s1)
            elif len(r) == 1:
                l = r[0]
                l = l.replace("</th>", "")
                l = l.replace("<thead>", "")
                r = l.split("<th>")
                if len(r) == 4:
                    s1 = "\t%5s       %25s %10s" % (r[1], r[2], r[3])
                    ss += s1 + "\n"
                    print(s1)
                elif len(r) == 9:
                    s1 = "%25s " % r[1]
                    for i in range(2, 9):
                        s1 += "%4s " % r[i]
                    ss += s1 + "\n"
                    print(s1)
                elif len(r[0]) > 0:
                    l = r[0]
                    s1 = "%4s %15s" % ("Year", "Winner")
                    ss += s1 + "\n"
                    print(s1)
                else:
                    #print(r)
                    pass
            else:
                #print(r)
                pass

    f = open("%s.txt" % tit.strip(), "w")
    f.write(ss)
    f.close()
